package com.example.api.advice;

import com.example.common.exc.AppException;
import com.example.common.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

/**
 * <>
 * <错误拦截 返回json给调用方>
 *
 * @Author jason_w
 * @Date 2019/1/9 0009 21:27
 * @see
 */
@ControllerAdvice
public class ExceptionHandlerAdvice {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);

    /**
     *<异常返回给前段JSON数据，前端根据错误处理>
     *@param
     *
     *@return
     *@Author jason_wang
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String exception(Exception ex, WebRequest request)throws Exception{
        LOGGER.error("ExceptionHandlerAdvice拦截到异常，e:{}",ex.getMessage());

        Result result= null;

        ex.printStackTrace();

        if (ex instanceof AppException){
            result.fail(ex.getMessage());
        }else {
            result.fail("未知异常");
        }
        return new ObjectMapper().writeValueAsString(result);
    }

    @ModelAttribute
    public void AddAttribute(Model model){
    }
}
